package com.tledu.web04.controller;

import com.tledu.web04.model.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        HttpSession session = req.getSession();
        String captcha = (String) session.getAttribute("captcha");
        // 验证码没有错误
        if (code == null || !code.equals(captcha)) {
            req.setAttribute("error", "验证码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }
        // 判断账号和密码有没有错误
        HashMap<String, Student> studentData = (HashMap<String, Student>) this.getServletContext().getAttribute("studentData");
        Student student = studentData.get(username);
       // 账号是否存在
        if (student == null) {
            req.setAttribute("error", "用户名不存在");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }
        // 密码是否争取
        if (!student.getPassword().equals(password)) {
            req.setAttribute("error", "密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }
        // 登录成功
        session.setAttribute("isLogin", true);
        session.setAttribute("loginUser", student);
        // 重定向
        resp.sendRedirect(req.getContextPath() + "/student");
    }
}
